
<template>
    <view class="openClass">
		<view v-if="!isExitLive || !endLive">
			<Live :url="url" :id="id" :status_at="status_at" :isCloseWebView="isCloseWebView" @backError="backError" @onBackfun="onBackfun" @backRefresh="onBackRefresh"></Live>
			<scroll-view scroll-y="true" id="liveMessage" :scroll-top="scrollTop" @scrolltolower="scrollToBottom" :scroll-into-view="scrollToView">
				<view class="live-message" ref="liveMessage">
					<view class="msg-list" >
						<view class="msg-item" v-for="(item, index) in webSocket_list" :key="index" :id="'msg-' + (index + 1)">
							<view class="msg-cont-g">
								<text class="name">
								    <u-tag text="主播" type="error" mode="light" shape="circle" size="mini" v-if="item.types == 10"/>
									{{item.name}}：
									 <text class="msg-content">{{item.content}}</text>
								</text>
							</view>
						</view>
					</view>
				</view>
			</scroll-view>
			<view class="foot-position" :style="`bottom:${keyboardHeight}px`">
			    <view class="foot-content">
					<input v-model="messages" class="foot-input" placeholder="与大家互动一下..." type="text" :adjust-position="false"  @keydown.enter="handleSendMsg" @keyboardheightchange="onKeyborardHeightChange" @blur="hideKeyboard" />
					<image class="image-item" src="/static/emoji.png"  mode="scaleToFill" @click="showEmoji()"></image>
					<view class="button" :class="{ disabled }" @click="handleSendMsg()">发送</view>
				</view>
				<view class="emoji-box" :style="{display: emojiVisible ? 'block' : 'none'}">
					<view class="emoji-title">表情</view>
					<view style="display: flex;flex-wrap: wrap;">
						<view v-for="item in emoji" :key="item" class="emoji-item" @click="handleChang(item)">
							<text style='font-size:36rpx;cursor:pointer'>{{item.emoji}}</text>
						</view>
					</view>
				</view>
			</view>
		</view>
		<view v-else class="exitLive-box">
			{{exitLiveData.content}}
		</view>
	</view>
</template>

<script>
  import Live from './components/live.vue';
  import store from '@/store/index'
  import { USER_ID, NICK_NAME } from '@/store/mutation-types'
  import storage from '@/utils/storage'
  import * as LiveApi from '@/api/live'
  import { checkLogin } from '@/core/app'
  import emoji from "../../static/emoji.json"
  
console.log(emoji);
  export default {
	components: {
		Live
	},
    data() {
      return {
         messages: '',
		 // 按钮禁用
		 disabled: false,
		 id: null,
		 webSocket_list: [],
		 url: '',
		 scrollTop: 0,
		 scrollToView: '', // 滚动目标元素ID
		 emoji: emoji,
		 emojiVisible:false,
		 keyboardStatus: false,
		 keyboardHeight: 0,
		 isCloseWebView:false,
		 isExitLive:false,
		 exitLiveData: {},
		 status_at: 0,
		 end_time: '',
		 // 是否已登录
		 isLogin: false,
		 endLives: false
      }
    },
	computed: {
		webSocketList () {
		  return store.getters.webSocketList;　　//需要监听的属性
		},
		connectState() {
			return store.getters.connectState
		},
		// 根据结束时间判断是否大于当前时间并结束直播播放
		endLive() {
			let date = new Date().getTime()
			if(this.end_time * 1000 < date) {
				this.isExitLive = true
				this.exitLiveData = {
				    name: '系统消息',
				    content: '直播已结束'
				}
			}
		    console.log(this.isExitLive, this.end_time * 1000 < date,'是否结束直播')
			return this.end_time * 1000 < date // this.end_time * 1000 < date
		}
	},
    watch: {
      webSocketList: {
        deep: true,
        handler: function(newVal, oldValue) {
          let that = this;
		  console.log(newVal, oldValue)
		  if(newVal.types == 9 || newVal.types == 10 || newVal.types == 11){
			  that.webSocket_list.push(newVal)
		  } else if(newVal.types == 12){
			  that.webSocket_list.push({
				  ...newVal,
				  name: '系统消息',
				  content: '直播暂时离开直播间'
			  })
		  } else if(newVal.types == 101){
			  that.webSocket_list.push({
				  ...newVal,
				  name: '系统消息',
				  content: '直播已结束'
			  })
			  that.isExitLive = true
			  that.exitLiveData = {
				  ...newVal,
				  name: '系统消息',
				  content: '直播已结束'
			  }
		  } else if(newVal.types == 102){
			  that.webSocket_list.push({
				  ...newVal,
				  name: '系统消息',
				  content: '用户被直播间禁言'
			  })
		  } else if(newVal.types == 103){
			  that.webSocket_list.push({
				  ...newVal,
				  name: '系统消息',
				  content: '用户被直播间解除禁言'
			  })
		  }
		 // 关键：更新滚动目标ID
		that.$nextTick(() => {
		  that.scrollToView = `msg-${that.webSocket_list.length}`;
		});
		  // that.scrollToBottom()
        }
      },
	  // 监听是否链接成功
	  connectState:{
		  deep: true,
		  handler: function(newVal, oldValue) {
		    let that = this;
		    console.log(newVal, oldValue,'是否连接成功websocket')
			if(newVal) {
				this.getLiveOpen()
			}
		  }
	  },
	  endLive:{
		  deep: true,
		  handler: function(newVal, oldValue) {
		    console.log(newVal, oldValue,'是否结束直播wacth')
		  }
	  }
    },
    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
		console.log(options,'id', this.connectState)
		// 当前订单ID
		this.id = options.id ? Number(options.id) : ''
		if(!storage.get('id')) {
			storage.set('id', options.id)
		} else if(options.id && storage.get('id') != options.id) {
			storage.set('id', options.id)
		}
		// 判断是否已登录
		this.isLogin = checkLogin()
		if(options.scene) {
			this.onRecordQuery(options)
		} else {
			if(this.isLogin) {
				if(!this.connectState) {
					this.$nextTick(() => {
						store.dispatch('connectSocket', 'U')
					})
				} else {
					this.getLiveOpen()
				}
			} else {
				this.getLiveOpen()
				// this.$navTo('pages/login/index', { id: options.id})
			}
		}

    },
	// 页面卸载
	onUnload(options) {
		console.log('from:' + options)
		// uni.navigateBack();
		this.isExitLive = false
		this.isCloseWebView = true
		// this.getLeave()  // 离开直播间
	},
	onBackPress(e) {//响应返回事件
		if (e.from === 'navigateBack') {  //这个地方必须要有的，否则会死循环
			return false;  
		} 
		let pages = getCurrentPages()
		let page = pages[0];
		console.log('点击返回....',e, pages);
	    this.$navTo(page.route)
		return true;
	},
    methods: {
		// 刷新数据
		refreshData() {
			
		},
		// 记录query参数
		onRecordQuery(query) {
		  const scene = getSceneData(query)
		   // 商户id
		  this.id = scene.uid ? parseInt(scene.uid) : ''
		  console.log('参数',scene, this.id)
		  if(this.isLogin) {
		   	    if(!this.connectState) {
					this.$nextTick(() => {
						store.dispatch('connectSocket', 'U')
					})
		        } else {
		   		    this.getLiveOpen()
		   	    }
		   }
		},
	  // 直播数据
	  getLiveOpen() {
		const app = this
	  	LiveApi.liveOpen({ id: app.id}).then(result => {
	  		console.log(result, '直播数据')
			app.url = result.data.url
			app.status_at = result.data.start_time  //result.data.start_time
			app.end_time = result.data.end_time // result.data.end_time
	    }).catch(() => {
			
		})
	  },
	  // 离开直播间
	  getLeave: function() {
		const app = this
		LiveApi.liveLeave({ id: app.id}).then(result => {
			console.log(result, '离开直播')
			app.$toast(result.message)
		}).catch(() => {
			
		})
	  },
	  // 滚动到底部
	  scrollToBottom() {
		const app = this
		this.$nextTick(() => {
		  // 创建查询对象
		  const query = uni.createSelectorQuery().in(this);
		  // 通过 ref 选择元素
		  query.select('#liveMessage').fields({
			size: true,        // 获取宽高
			scrollOffset: true // 获取滚动位置
		  }, (res) => {
			console.log('元素信息:', res);
			app.scrollTop = res.scrollHeight
			uni.pageScrollTo({
			  scrollTop: res.scrollHeight, // 滚动到目标元素的顶部
			  duration: 300, // 滚动动画的时长
			});
			// 输出结果示例：
			// {
			//   width: 375,
			//   height: 500,      // 可见区域高度
			//   scrollHeight: 2000, // 内容总高度
			//   scrollTop: 0      // 当前滚动位置
			// }
		  }).exec();
		}) 
	  },
	  // 发送消息
	  handleSendMsg() {
		const app = this
		if (app.messages.trim()) {
			LiveApi.liveSend({
				id: app.id,
				"content": app.messages,
				"name": storage.get(NICK_NAME)
			}).then(result => {
				console.log(result, '发送消息')
				app.status = result.data.status
				if(result.data && result.data.status == 20) {
					app.webSocket_list.push({
					  types: 11,
					  name: storage.get(NICK_NAME),
					  content: app.messages
					})
					console.log(app.webSocket_list, '消息')
				}
				app.messages = ''
			}).catch(() => {
				
			})
		}
		// store.dispatch('sendSocketMessage', obj)
	  },
	  showEmoji() {
		this.emojiVisible = !this.emojiVisible  
	  },
	  // 选择表情
	  handleChang(item) {
		  this.messages = this.messages + item.emoji
		  this.emojiVisible = !this.emojiVisible  
	  },
	  // 键盘相关事件
	  onKeyborardHeightChange(event) {
	  	console.log('键盘相关事件',event, this.keyboardStatus)
	  	this.keyboardHeight = event.detail.height;
	  },
	  
	  // 失去焦点 - 隐藏键盘
	  hideKeyboard() {
	  	this.keyboardStatus = false;
	  	this.keyboardHeight = 0;
	  },
	  backError() {
		  // this.getLiveData()
		  // const app = this
		  // app.url = app.url
	  },
	  onBackfun(val) {
		  this.isCloseWebView = val.isCloseWebView
	  },
	  onBackRefresh(data) {
		  console.log('刷新11',data)
		  this.getLiveOpen()
	  }
    }
  }
</script>

<style lang="scss" scoped>
.openClass{
	#liveMessage{
		// #ifdef H5
		max-height: 57vh;
		// #endif
		//#ifdef MP-WEIXIN
		max-height: 57vh;
		//#endif
		//#ifdef APP-PLUS
		max-height: 98vh;
		//#endif
		margin-top: 10rpx;
	}
	.live-message{
		padding: 20rpx 6rpx;
		// max-height: 54vh;
		overflow-y: auto;
		//#ifdef APP-PLUS
		margin-top: 35vh;
		//#endif
		// #ifdef MP-WEIXIN
		// margin-top: 35vh;
		// #endif
		.msg-item{
		    display: flex;
		    align-items: flex-start;
		    margin-top: 16rpx;
			.msg-cont-g{
				display: flex;
				align-items: center;
			}
			.msg-grade{
			    width: 80rpx;
				 border-radius: 50%;
			}
			.name{
			   color: #8ce7ff;
			   margin:0 20rpx;
			}
			.msg-content{
				color: #333;
			    line-height: 50rpx;
			}
		}
	}
	.foot-position{
		position: fixed;
		bottom: 25px;
		left: 6rpx;
		padding-right: 6rpx;
		width:100%;
		z-index: 999;
		transition-property: bottom;
		transition-duration: 100ms;
		.foot-content{
			display: flex;
			align-items: center;
			background-color: #f0f0f0;
			margin: 20rpx 20rpx;
			padding: 16rpx;
			border-radius: 20rpx;
			.image-item{
				width:46rpx;
				height:46rpx;
				margin-right:16rpx;
			}
			.foot-input{
				flex: 1;
			}
			.button {
			  width: 120rpx;
			  height: 58rpx;
			  background: linear-gradient(to right, #12a15c, #12a15c);
			  color: #fff;
			  font-size: 26rpx;
			  border-radius: 20rpx;
			  letter-spacing: 5rpx;
			  display: flex;
			  justify-content: center;
			  align-items: center;
			
			  // 禁用按钮
			  &.disabled {
			    opacity: 0.6;
			  }
			}
		}
		.emoji-box{
			padding: 16rpx;
			max-height: 250rpx;
			overflow: auto;
			background-color: #fff;
			.emoji-title{
				line-height: 40rpx;
				font-weight: bold;
			}
			.emoji-item{
			    margin-right: 16rpx;
			    margin-bottom: 10rpx;
			}
		}
	}
	.exitLive-box{
		padding-top: 200rpx;
		text-align: center;
	}
}
</style>